﻿using PSI.Helper;
using Spring.Data;
using Spring.Data.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace PSI.Services {
    public class PSIBaseService {
        private Spring.Data.Generic.AdoTemplate db {
            get { return DBHelper.AdoTemplate; }
        }

        protected IDbParameters CreateDbParameters() {
            return db.CreateDbParameters();
        }

        /// <summary>
        /// 执行数据库事务操作
        /// </summary>
        /// <param name="td"></param>
        protected void WithTransaction(TransactionDelegateEx td) {
            DBHelper.TransactionTemplate.WithTransaction(td);
        }

        /// <summary>
        /// 执行类似 select count(*) from ... 的语句，返回结果值
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        protected int QueryCount(string sql) {
            return db.QueryCount(sql, db.CreateDbParameters());
        }

        /// <summary>
        /// 执行类似 select count(*) from ... 的语句，返回结果值
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        protected int QueryCount(string sql, IDbParameters parameters) {
            return db.QueryCount(sql, parameters);
        }

        /// <summary>
        /// 执行insert、update、delete等SQL语句
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        protected int Execute(string sql, IDbParameters parameters) {
            return db.Execute(sql, parameters);
        }

        protected int Execute(string sql) {
            return db.Execute(sql, CreateDbParameters());
        }

        protected void Query(string sql, RowCallbackDelegate rowCallbackDelegate) {
            db.QueryWithRowCallbackDelegate(CommandType.Text, sql, rowCallbackDelegate);
        }

        protected void Query(string sql, IDbParameters parameters, RowCallbackDelegate rowCallbackDelegate) {
            db.QueryWithRowCallbackDelegate(CommandType.Text, sql, rowCallbackDelegate, parameters);
        }

        protected T QueryObject<T>(string sql, IDbParameters parameters,
            QueryObjectDelegate<T> rowCallbackDelegate) {
                return db.QueryObject<T>(sql, rowCallbackDelegate, parameters);
        }
    }
}